<?php
/**
 * Created by PhpStorm.
 * User: FoxxxZhu
 * Date: 2018/1/3
 * Time: 16:11
 */

namespace Forxx\Api;

use Forxx\RedisCache;

class VisitLog
{
    CONST LOG_QUEUE_NAME = "visit::log";
    CONST LOG_SORT_NAME = "visit::log::sort::";
    protected static $log;
    public function __construct()
    {

    }

    public static function instance()
    {
        if(empty(self::$log))
        {
            self::$log = new Static();
        }
        return self::$log;
    }

    public function recoveryFromDb($size = 30)
    {
        $data = Video::getHotList(1,$size);
        foreach($data as $d)
        {
            $this->addLog($d['id']);
        }
    }

    public function addLog($id)
    {
        $sortKey = self::LOG_SORT_NAME.$id;
        $num = RedisCache::instance()->incr($sortKey);
        if($num <= 1)//目前不存在
        {
            RedisCache::instance()->lpush(self::LOG_QUEUE_NAME,$id);
        }
    }

    public function get($size,$page = 1)
    {
        $data = RedisCache::instance()->sort(self::LOG_QUEUE_NAME,"BY",self::LOG_SORT_NAME."*","DESC");
        if(empty($data))
        {
            $this->recoveryFromDb();
            return $this->get($size,$page);
        }
        else{
            return array_slice($data,($page - 1) * $size,$size);
        }
    }

    public function clearAll()
    {
        $i = 0;
        while(true)
        {
            $id =  RedisCache::instance()->lindex(self::LOG_QUEUE_NAME,$i);
            if($id != null)
            {
                $sortKey = self::LOG_SORT_NAME.$id;
                RedisCache::instance()->del($sortKey);
            }
            else
            {
                break;
            }
            $i++;
        }
        RedisCache::instance()->del(self::LOG_QUEUE_NAME);
    }
}
